<template>
  <view class="merchant-container">
    <view class="form-container default-box-shadow">
      <u-form :model="userForm" ref="uForm" label-width="150">
        <u-form-item label="设置头像" prop="avatar">
          <image
            :src="userForm.avatar"
            mode="aspectFill"
            class="author-avatar"
          />
          <view class="upload-right">
            <view @click="handleRandom" class="avatar-btn">随机更改头像</view>
            <view @click="handleUploadAvatar" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">自定义上传</view>
          </view>
          <!-- <Upload
          ref="uUpload"
          :action="uploadParams.action"
          :header="{
            'Authorization': 'Bearer ' + token // token
          }"
          height="200"
          upload-text="选择"
          :limitType="uploadParams.limitType"
          :source-type="['album']"
          :max-count="uploadParams.maxCount"
          :type="uploadParams.uploadType"
          del-bg-color="#56d39d"
          :auto-upload="true"
          :file-list="uploadParams.fileList"
          @on-remove="removeImage"
          @on-uploaded="uploadSuccess"></Upload> -->
        </u-form-item>
        <u-form-item label="平台昵称" prop="author_name">
          <u-input v-model="userForm.author_name" :disabled="merchantId > 0 && (audit_status === 'review' || audit_status === 'success')" placeholder="请输平台昵称" />
        </u-form-item>
        <u-form-item label="推广口令" prop="code">
          <u-input v-model="userForm.code" :disabled="merchantId > 0 && (audit_status === 'review' || audit_status === 'success')" placeholder="请输入推广口令（字母或数字）" />
          <view slot="right" class="reload-btn" @click="getRandomCode">
            <u-icon v-if="!merchantId" size="38" name="reload"></u-icon>
          </view>
        </u-form-item>
        <u-form-item label="邀请码" prop="merchant_source_code">
          <u-input v-model="userForm.merchant_source_code" placeholder="请输入您的上级邀请码（选填）" />
        </u-form-item>
        <u-form-item label="手机号码" prop="merchant_phone">
          <u-input v-model="userForm.merchant_phone" :disabled="merchantId > 0 && (audit_status === 'review' || audit_status === 'success')" placeholder="请输入手机号码" />
        </u-form-item>
        <u-form-item label="联系方式" :border-bottom="false" prop="merchant_contact_information">
          <u-input v-model="userForm.merchant_contact_information" :disabled="merchantId > 0 && (audit_status === 'review' || audit_status === 'success')" placeholder="请输入微信号" />
        </u-form-item>
      </u-form>
    </view>
    <!-- 提示 -->
    <view class="tip">请如实填写您的账户信息，方便快速与您联系和审核！</view>
    <view v-if="audit_status === 'review'" class="sumbit-button review-button">审核中</view>
    <view v-else-if="audit_status === 'success'" class="sumbit-button success-button">审核成功</view>
    <view v-else-if="audit_status === 'reject'" class="sumbit-button" @click="subscribeMessageFn">重新提交</view>
    <view v-else class="sumbit-button" @click="subscribeMessageFn">提交</view>
    <!-- 关注微信公众号 -->
    <u-popup
			v-model="officalShow"
			mode="center"
      :closeable="false"
      :mask-close-able="false"
			border-radius="16"
			width="600">
			<view class="popup-content1">
				<view class="title">注册成功</view>
        <image
          v-if="platformInfo"
          :src="platformInfo.official_qrcode"
          mode="scaleToFill"
          class="qrcode"
        />
        <!-- <view class="offical-tips">方便后面操作，长按扫码关注公众号</view> -->
        <view class="btn-container">
          <u-button class="btn" plain hover-class="none" @click="jumpIndexPage">跳转首页</u-button>
        </view>
			</view>
		</u-popup>
  </view>
</template>

<script>
  import { merchantApply, merchantInfoByUserId, randomCode } from '@/api/applet';
  import { platformInfoByBusinessId } from '@/api/applet';
  import { getUserInfoById } from "@/api/user";
  import { authorization } from '@/utils/login.js';
  import { mapGetters } from 'vuex';
  import Upload from '@/components/upload/upload';
  import config from '@/utils/config';
  import { checkText } from '@/utils/index';
  export default {
    components: {
      Upload
    },
    data() {
      return {
        show: true,
        merchantId: 0,
        agreement: false,
        officalShow: false,
        audit_status: null,
        source_code: null,
        platformInfo: {},
        randomNum: 1,
        uploadParams: {
          limitType: ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp'],
          maxCount: 1,
          uploadType: 'image',
          action: `${config.baseApi}/client/upload/uploadImg`,
          fileList: [],
        },
        userForm: {
          id: '',
          avatar: 'https://design-aliyun.tsgzs.com/author-default-avatar/1.jpg',
          code: null, // 推广口令
          author_name: null, // 达人昵称
          merchant_contact_information: null, // 联系方式qq/微信
          merchant_source_code: null, // 上级邀请口令
          merchant_phone: null, // 商家联系电话
          merchant_flatform: null, // 入驻申请平台
          password: '123456',
          show_make: config.appletType
        },
        rules: {
          merchant_phone: [
            {
              min: 11,
              max: 11,
              required: true, 
              message: '请输入长度为11位的手机号码', 
              trigger: ['change', 'blur'],
            }
          ],
          author_name: [
            { 
              required: true, 
              message: '请输入您的昵称', 
              trigger: ['change', 'blur'],
            }
          ],
          merchant_contact_information: [
            { 
              required: true, 
              message: '请输入微信/QQ', 
              trigger: ['change', 'blur'],
            }
          ],
          code: [
            {
              required: true,
              message: '请输入推广口令', 
              trigger: ['change', 'blur']
            }
          ],
          avatar: [
            {
              required: true,
              message: '请上传头像', 
              trigger: ['change', 'blur']
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'token',
        'userInfo',
        'appletInfo'
      ])
    },
    onLoad() {
      console.log(45354235,this.$route)
      this.handleRandom();
      this.getMerchantInfoByUserId();
      this.userInfoById();
      this.getPlatformInfoByBusinessId();
    },
    methods: {

      // 随机头像
			handleRandom() {
				let randomNum = this.randomNumFn(1, 66);
				this.userForm.avatar = `https://design-aliyun.tsgzs.com/author-default-avatar/${randomNum}.jpg`;
				this.randomNum = randomNum;
			},
      // 随机数
			randomNumFn(min, max) {
				let choices = max - min+ 1;
				return Math.floor(Math.random() * choices + min);
			},

			// 上传头像
			handleUploadAvatar() {
				let that = this;
				uni.chooseImage({
					count: 1,
					success: res => {
						let temp = res.tempFilePaths[0];
						uni.uploadFile({
							url: `${config.baseApi}/client/upload/uploadImg`,
							filePath: temp,
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + that.token // token
							},
							success: (imgRes) => {
								let result = JSON.parse(imgRes.data)
								if (result.code === 200 && result.data) {
									//开始检测
									that.userForm.avatar = result.data.cover_path;
									uni.showToast({
										icon: 'none',
										title: '上传成功！'
									})
								} else {
									uni.hideLoading();
									uni.showToast({
										icon: 'none',
										title: '上传失败，请重试'
									})
								}
							},
							fail: function (e) {
								console.log(e);
							}
						});
					},
					fail(e) {
						console.log(e);
					}
				})
			},

      // 获取平台详情
      getPlatformInfoByBusinessId() {
        platformInfoByBusinessId().then(result => {
          if (result && result.code === 200) {
            this.platformInfo = result.data;
          }
        })
      },

      // 选择创作类型
      checkboxGroupChange(e) {
        this.userForm.artworks_type = e;
      },

      // 获取入驻信息
      getMerchantInfoByUserId() {
        merchantInfoByUserId().then(result => {
          if (result && result.data) {
            const data = result.data;
            this.merchantId = data.id;
            this.audit_status = data.audit_status;
            data.artworks_type = data.artworks_type ? JSON.parse(data.artworks_type) : [];
            this.userForm = {
              id: data.id,
              avatar: data.avatar, // 达人头像
              author_name: data.author_name, // 达人昵称
              merchant_contact_information: data.merchant_contact_information, // 联系方式qq/微信
              code: data.userInfo.invitation_code, // 推广口令
              merchant_source_code: data.userInfo.source_code, // 上级邀请口令
              merchant_phone: data.merchant_phone, // 联系电话
            }
            if (data.avatar) {
              this.uploadParams.fileList = [{
                url: data.avatar
              }];
            }
            this.userInfoById();
          } else {
            this.getRandomCode();
            this.userInfoById();
          }
        })
      },

      // 获取用户信息和邀请码
      userInfoById() {
        getUserInfoById().then(result => {
          if (result && result.data) {
            this.source_code = result.data.source_code;
            this.userForm.merchant_source_code = result.data.source_code;
          }
        })
      },

      // 获取随机口令
      getRandomCode() {
        randomCode().then(result => {
          if (result && result.data) {
            this.userForm.code = result.data.toString();
          }
        })
      },

      // 订阅消息
      subscribeMessageFn() {
        const that = this;
        // #ifdef MP-WEIXIN
        const subscribeMessageId = this.appletInfo ? this.appletInfo.subscribe_message_id : '';
        if (subscribeMessageId) {
          uni.requestSubscribeMessage({
            tmplIds: [ subscribeMessageId ],
            success (res) {
              that.sumbitMerchantApply();
            },
            fail (res) {
              console.log(res);
              that.sumbitMerchantApply();
            }
          })
        } else {
          that.sumbitMerchantApply();
        }
        // #endif

        // #ifndef MP-WEIXIN
        that.sumbitMerchantApply();
        // #endif

      },

      // 提交申请
      merchantApply() {
        const that = this;
        merchantApply(this.userForm).then(async result => {
          uni.hideLoading();
          if (result && result.code === 200) {
            uni.showToast({
              title: '提交成功',
              icon: 'success',
              mask: true
            })
            await this.$store.dispatch('setIsLogin', true);
            authorization({
              source_code: '',
              code: '',
              resetToken: true
            }).then(result => {
              that.officalShow = true;
            });
            // setTimeout(() => {
            //   this.getMerchantInfoByUserId();
            //   uni.switchTab({
            //     url: '/pages/index/index'
            //   })
            // }, 1000)
          }
        }).catch(() => {
          uni.hideLoading();
        })
      },

      // 跳转首页
      jumpIndexPage() {
        uni.switchTab({
          url: '/pages/index/index'
        });
      },

      // 上传成功
      uploadSuccess(data) {
        let avatar = '';
        data.forEach(item => {
          avatar = item.response.data.cover_path
          return;
        })
        this.userForm.avatar = avatar;
      },

      // 删除图片
      removeImage() {
        this.userForm.avatar = '';
      },

      // 提交申请
      sumbitMerchantApply() {
        let merchant_flatform = null;
        // #ifdef MP-WEIXIN
        merchant_flatform = 'wx_mini';
        // #endif
        // #ifdef MP-QQ
        merchant_flatform = 'qq_mini';
        // #endif
        // #ifdef MP-KUAISHOU
        merchant_flatform = 'ks_mini';
        // #endif
        // #ifdef MP-TOUTIAO
        merchant_flatform = 'tt_mini';
        // #endif
        // #ifdef H5
        merchant_flatform = 'wx_official';
        // #endif
        this.userForm.merchant_flatform = merchant_flatform;
        uni.showLoading({
          title: '提交中...',
          mask: true
        })
        this.$refs.uForm.validate(async valid => {
          if (valid) {
            if (!/^1[23456789]\d{9}$/.test(this.userForm.merchant_phone)) {
              uni.hideLoading();
              uni.showToast({
                title: '手机号码电话格式错误',
                icon: 'none',
              });
              return;
            }
            this.userForm.audit_status = this.userForm.id ? 'review' : '';

            // 检查文本内容
            const flag = await checkText(this.userForm.author_name);

            this.merchantApply();
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '验证失败,请检查',
              icon: 'none',
            });
            console.log('验证失败');
          }
        });
      }
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
    }
  }
</script>

<style lang="scss">
  page{
    background-color: #f8f8f8;
  }

  .merchant-container{
    padding: 24rpx;

    .form-container{
      background-color: #fff;
      padding: 24rpx;

      .upload-container{
        width: 100rpx;
        height: 100rpx;
      }

      .bind-title{
        font-size: 28rpx;
        text-align: center;
        color: #333;
        padding: 6rpx 0;
      }
      .bind-btn{
        background-color: $uni-color-primary;
        color: #fff;
      }
    }

    .tip{
      margin-top: 40rpx;
      font-size: 24rpx;
      color: #888;
    }

    .sumbit-button{
      background-color: $uni-color-primary;
      color: #ffff;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      text-align: center;
      font-size: 32rpx;
      margin-top: 40rpx;
    }

    .review-button{
      background: rgba($color: #888, $alpha: 0.6);
    }

    .success-button{
      background: rgba($color: #67c23a, $alpha: 0.6);
    }

    &-title{
      font-size: 42rpx;
      margin-bottom: 12rpx;
    }

    &-des{
      font-size: 28rpx;
      color: #888;

      &-item{
        margin-bottom: 6rpx;
      }
    }
  }

  .popup-content1{
		padding: 32rpx;
		background-color: #fff;
		color: #fff;
    position: relative;
    text-align: center;

    .title{
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 24rpx;
    }

    .qrcode{
      width: 420rpx;
      height: 420rpx;
      margin-bottom: 24rpx;
    }

    .wechat-number{
      color: #4b4b5c;
    }

    .btn-container{
			display: flex;
			padding-top: 32rpx;
			justify-content: space-between;

			.btn{
				flex: 1;
        background-color: $uni-color-primary;
        color: #fff;
        border-color: $uni-color-primary;
			}

      .btn::after,
      .btn::before{
        display: none;
      }
		}

    .offical-tips{
      color: #333;
    }
	}

  .author-avatar{
		width: 148rpx;
		height: 148rpx;
		border-radius: 50%;
		border: 2rpx solid #eaeaea;
		display: block;
	}

	.upload-right{
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		width: 200rpx;
		margin-left: 24rpx;

		.avatar-btn{
			margin-bottom: 28rpx;
		}

		.avatar-btn,
		.slot-btn{
			background: #e0eefc;
			color: $uni-color-primary;
			padding: 0 12rpx;
			width: 180rpx;
			height: 48rpx;
			line-height: 48rpx;
			font-size: 24rpx;
			text-align: center;
			border-radius: 8rpx;
		}
	}
</style>
